import { NodeStatus } from "../NodeStatus";
import { ControlNode } from "./ControlNode";


/**
 * 同SequenceNode，不同之处在于如果某个子节点返回FAILURE，返回FAILURE，终止所有节点的执行。
 * 但不复位current_child_idx_。所以当再次tick()时，从FAILURE的子节点开始。
 */
export class SequenceStarNode<T> extends ControlNode<T> {
    private __current_index = 0;
    constructor(name: string,blackboard: T) {
        super(name,blackboard);
    }

    Tick(): NodeStatus {
        this.status = NodeStatus.RUNNING;
        while (this.__current_index < this.numChildren) {
            const child = this.$children[this.__current_index];
            const child_status = child.Evaluate();
            switch (child_status) {
                case NodeStatus.RUNNING:
                    return child_status;
                case NodeStatus.FAILURE:
                    this.HaltChildren(this.__current_index);
                    return child_status;
                case NodeStatus.SUCCESS:
                    this.__current_index++;
                    break;
                case NodeStatus.IDLE:
                    throw new Error("NodeStatus.IDLE is not a valid status");
                default:
                    throw new Error("Unknown NodeStatus");
            }
        }
        if (this.__current_index === this.numChildren) {
            this.HaltChildren();
            this.__current_index = 0;
        }
        return NodeStatus.SUCCESS;
    }
}